package util.stack;

import java.lang.reflect.Array;

/**
 * 顺序栈
 * @author Huzz
 * @created 2021-10-09 16:12
 * @param <T>
 */
public class ArrayStack<T> {

    private static final int DEFAULT_SIZE = 10;

    /**
     * 长度
     */
    private int count;

    /**
     * 存放栈元素的数组
     */
    private T[] array;

    public ArrayStack(Class<T> type) {
        this(type, DEFAULT_SIZE);
    }

    public ArrayStack(Class<T> type, int size) {
        this.count = 0;
        this.array = (T[]) Array.newInstance(type, size);
    }

    /**入栈
     *
     * @param val
     */
    public void push(T val){
        this.array[count++] = val;
    }

    /**
     * 查找栈顶元素
     * @return
     */
    public T peek(){
        return this.array[count - 1];
    }

    /**
     * 出栈
     * @return
     */
    public T pop(){
        return this.array[--count];
    }

    /**
     * 栈的长度
     * @return
     */
    public int size(){
        return this.count;
    }

    /**
     * 是否为空
     * @return
     */
    public boolean isEmpty(){
        return this.count == 0;
    }

    /**
     * 打印栈
     */
    public void printArrayStack(){
        if (this.count == 0) {
            System.out.println("The Stack is Empty.");
            return;
        }
        StringBuilder stringBuilder = new StringBuilder("[");
        for (int i = 0; i < count; i++) {
            stringBuilder.append(this.array[i] + ", ");
        }
        stringBuilder.replace(stringBuilder.lastIndexOf(", "), stringBuilder.length(), "]");
        System.out.println(stringBuilder);
    }
}

